package cn.linshu.security.jwt.service.impl;

import cn.linshu.security.jwt.dto.ResultCode;
import cn.linshu.security.jwt.entity.SysResource;
import cn.linshu.security.jwt.entity.SysUser;
import cn.linshu.security.jwt.mapper.SysUserMapper;
import cn.linshu.security.jwt.service.SystemService;
import cn.linshu.security.jwt.util.Asserts;
import cn.linshu.security.jwt.util.JwtTokenUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * -*- coding: utf-8 -*-
 *
 * @Author linnin
 * @Name springboot3-labs-master
 * @Time 2025/2/3 23:48
 * @Note
 * @For
 * @Out Copyright© 2025 linnin
 */

/* coding: utf-8 */

@Slf4j
@Service
public class SystemServiceImpl implements SystemService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public String login(String username, String password) {
        String token = "";
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
            if(userDetails == null) {
                return token;
            }
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                //密码不匹配
                Asserts.fail(ResultCode.PASSWORD_INCORRECT.getCode(), ResultCode.PASSWORD_INCORRECT.getMessage());
            }
            if (!userDetails.isEnabled()) {
                //账号被禁用
                Asserts.fail(ResultCode.ACCOUNT_DISABLED.getCode(), ResultCode.ACCOUNT_DISABLED.getMessage());
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            log.error("登录异常:{}", e.getMessage());
        }
        return token;
    }


    @Override
    public UserDetails loadUserByUsername(String username) {
        //获取用户信息
        SysUser sysUser = getSysUserByUsername(username);
        if (sysUser != null) {
            List<SysResource> resourceList = new ArrayList<>();
            return new SysUserDetails(sysUser, resourceList);
        }
        //账号不存在
        Asserts.fail(ResultCode.USER_NOT_FOUND.getCode(), ResultCode.USER_NOT_FOUND.getMessage());
        return null;
    }

    @Override
    public SysUser getSysUserByUsername(String username) {
        //先从缓存中获取数据
        //TODO
        //缓存中没有从数据库中获取
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if (sysUser != null) {
            //将数据库中的数据存入缓存中
            //TODO
            return sysUser;
        }
        return null;
    }

//    @Bean
//    public PasswordEncoder passwordEncoder() {
//        return new BCryptPasswordEncoder();
//    }
}

